'''
Created on 2009-8-26

@author: lz
'''

from os import listdir
from os.path import splitext, join, split
import binascii
import cPickle as pickle
from ConfigParser import ConfigParser, ParsingError

g_path_script = join(split(__file__)[0], 'script')
g_path_pickle = join(split(__file__)[0], 'pkl.txt')


def tranhextext(s):
    xbegin = s.find('0x')
    if xbegin != -1:
        s = s[xbegin + 2:]
    return binascii.a2b_hex("".join(s.split()))

class SampleFamily:
    def __init__(self):
        self.name = None
        self.Method = None
        self.Type = None
        self.Major = None
        self.Imports = None
        self.Signs = None
        self.Fix = None
        self.Decrypt = None
        self.Param = None
    
    def set_info(self, name, Method, Type, Major, Import1, Import2, Import3, Sign1, Sign2, Sign3, Fix, Decrypt, Param):
        self.name = name
        self.Method = Method
        self.Type = Type
        self.Major = Major
        self.Imports = (Import1, Import2, Import3) 
        self.Signs = (Sign1, Sign2, Sign3)
        self.Fix = Fix
        self.Decrypt = Decrypt
        self.Param = Param
    
def get_family(filename):
    cp = ConfigParser()
    try:
        cp.read(filename)
    except ParsingError:
        pass
    
    family = SampleFamily()
    family.set_info(name = cp.get('Common', 'Name'), 
                     Method = cp.get('Common', 'Method'),
                     Type = cp.get('Common', 'Type'),
                     Major = tranhextext(cp.get('Major', 'Sign')),
                     Import1 = cp.get('Detail', 'Import1'), 
                     Import2 = cp.get('Detail', 'Import2'),
                     Import3 = cp.get('Detail', 'Import3'),
                     Sign1 = tranhextext(cp.get('Detail', 'Sign1')), 
                     Sign2 = tranhextext(cp.get('Detail', 'Sign2')), 
                     Sign3 = tranhextext(cp.get('Detail', 'Sign3')), 
                     Fix = cp.get('Append', 'Fix'),
                     Decrypt = cp.get('Append', 'Decrypt'), 
                     Param = cp.get('Append', 'Param')
                     )
    return family

def get_familys():
    
    family_list = []
    script_dir = join(split(__file__)[0], 'script')
    
    for item in listdir(script_dir):
        if splitext(item)[1] == '.tjs':
            family_list.append(get_family(join(g_path_script, item)))
            
    return family_list

def get_pickle_familys():
    pickle_file = open(g_path_pickle, 'rb')
    family_list = pickle.load(pickle_file)
    pickle_file.close()
    return family_list

def dump_familys():
    pickle_file = open(g_path_pickle, 'wb')
    pickle.dump(get_familys(), pickle_file)
    pickle_file.close()
   
if __name__ == '__main__':
    dump_familys()
    get_pickle_familys()